<template>
  <el-table ref="table" v-if="showTable" :data="table" :show-summary="showSummary" :row-class-name="tableRowClassName" size="mini" stripe border fit highlight-current-row @sort-change="sortChange" >
    <el-table-column  fixed="left" v-if="showExpand">
      <template slot-scope="scope">
        <div style="text-align:center" v-if="scope.row.level<3" @click="expand(scope)">
          <i v-if="scope.row.isExpand" class="el-icon-arrow-down" ></i>
          <i v-else class="el-icon-arrow-right" ></i>
        </div>
      </template>
    </el-table-column>
    <template v-for="(item, index) in key_mapper">
      <el-table-column :sortable = "sortableIn(item.key)" :hover= "index" :key = "2*index +1" :prop = "item.key" :label="item.name" :min-width="minWidth" :formatter="formatter" :fixed="fiexd(item)" width="145px" :width="item.width">
        <template slot-scope="scope" slot="header">
          <el-tooltip :content = "item.description" :disabled="!item.description" effect="dark" placement="top">
            <span :class="item.class">{{ item.name }}</span>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <span  :class="[scope.row[item.key] < 0?'negative'+' '+item.class:null,(item.key=='game_name' && scope.row.level)?`name-level${scope.row.level}` +' '+item.class:item.class]" >
            {{ scope.row[item.key] ? item.value_type === 'float' ? scope.row[item.key].toFixed(2) : item.value_type === 'long' ? parseInt(scope.row[item.key]) : scope.row[item.key]:0 }} {{ item.is_percentage?'%':null }}
          </span>
        </template>
      </el-table-column>
    </template>
    <slot/>
  </el-table>
</template>

<script>
  import { fixed3 } from '@/utils'
  import AnalyseTable from './index.vue'
  import { sendForm } from '@/utils/'

  export default {
    name: 'AnalyseTable',
    components:{
      AnalyseTable
    },
    computed: {
      game_type(){
        return this.parent.chooseOptions.map(item => item.value)
      }
    },
    inject: {
      parent: { default: {} }
    },
    props: {
      level:{
        type:Number,
        default:-1
      },
      showExpand:{
        type:Boolean,
        default:false
      },
      isCancelFiexd:{
        type:Boolean,
        default:false
      },
      tableData: {
        type: Array,
        default: function() {
          return []
        }
      },
      key_mapper: {
        type: Array,
        default: function() {
          return []
        }
      },
      size: {
        type: String,
        default: 'mini'
      },
      minWidth: {
        type: Number,
        default: 130
      },
      sortable: {
        type: [Boolean, Array],
        default: function() {
          return false
        }
      },
      showSummary: {
        type: [Boolean, Array],
        default: false,
        required: false
      }
    },
    data() {
      return {
        table: this.showExpand?this.addIsExpandAndLevel(this.trans(this.tableData)):this.trans(this.tableData),
        showTable: true,
        sub_key_mapper:[],
        sub_tableData:[],
      }
    },
    watch: {
      tableData() {
        this.table = this.showExpand?this.addIsExpandAndLevel(this.trans(this.tableData)):this.trans(this.tableData)
        this.showTable = false
        this.$nextTick(() => (
          this.showTable = true
        ))
        this.$forceUpdate()
      },

    },
    deactivated() {
    },
    methods: {
       expand(scope){
         scope.row.isExpand = !scope.row.isExpand;
         if(scope.row.isExpand){
           this.open(scope)
         }else{
           this.close(scope)
         }
       },
       open(scope){
        const row = scope.row;
        let index = scope.$index;
         let {level}=row
        let currentLevel = level+ 1;
        let params = {}
        // 二级
        if(currentLevel == 2) params = {user_id:row._user_id,game_type:this.game_type}
        // 三级
        if(currentLevel == 3) params = {user_id:row._user_id,game_type:this.getGameType(row.game_name),game_id_list:this.getGameIdList(row.game_name)}
        if(this.parent.queryFrom.display_dimension===1){
          Object.assign(params,{time_range:[`${row.day} 00:00:00`,`${row.day} 23:59:59`]})
        }
        this.getData(params).then(d => {
          this.addIsExpandAndLevel(d).forEach(item => {
            item.level=currentLevel
            this.table.splice(index+1,0,item);
          })
        });
       },
       close(scope){
        const row = scope.row;
        let index = scope.$index;
        const level = row.level;

        let deleteNum = 0;
        for(let i=index+1;i<this.table.length;i++){
          const item = this.table[i];
          if(item.level <= level){
            break;
          }
          deleteNum ++;
        }
        this.table.splice(index+1,deleteNum);
       },
      getData(params = {},data = this.parent.queryFrom, API = this.parent.API, key_mapper = 'sub_key_mapper', tableData = 'sub_tableData') {
        this.$loading({ lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.15)' })
        let send = Object.assign({}, data, { page: 1, size: this.parent.size, page_id: this.parent.page_id },params)

        send = sendForm(send)
        return new Promise((resolve,reject) =>{
          // this.getExcel(send)
          API(send).then(res => {
            this.sendData = JSON.parse(JSON.stringify(send))
            this.resData = res.data
            resolve(res.data.list.map(item => {
              const data = {}
              for (const item1 in item) {
                if (item[item1]) {
                  data[item1] = item[item1].sum || item[item1]
                } else if (item[item1] === '') {
                  data[item1] = ' '
                } else {
                  data[item1] = null
                }
              }
              return data
            }))
            // if (res.data.key_mapper) {
            //   this[key_mapper] = res.data.key_mapper
            // }
        })

        }, err => {
          this.$message({ type: 'error', message: err.response.data.msg })
        })
      },
      fiexd(item){
        if(this.isCancelFiexd) return null
        return item.key=='day'||(item.key&&item.key=='game_name'&&this.table[0].game_name!='汇总')||(item.key&&item.key=='room_name'&&this.table[0].room_name!='汇总')||(item.key=='limit')||(item.key=='hour')||(item.key=='_chn')||(item.key=='_user_id')||(item.key=='registered_at')||(item.key=='chn')||(item.key=='key'&&this.table[0].key!='汇总')? 'left':null
      },
      tableRowClassName({ row, rowIndex }) {
        if (row.day === '环比') {
          return 'warning-row'
        }
        return ''
      },
      linkRow(row) {
        this.$emit('linkRowData', row)
      },
      trans(tableData) {
        // console.log(this.tableData)
        return tableData.map(item => {
          const obj = item
          this.key_mapper.forEach(item1 => {
            if (`${obj[item1.key]}` && item1.enum && (JSON.stringify(item1.enum) !== '{}')) {
              // debugger
              obj[item1.key] = item1.enum[obj[item1.key]] ? item1.enum[obj[item1.key]].name : obj[item1.key]
            }
          })
          return obj
        })
      },
      addIsExpandAndLevel(tableData){
        return tableData.map(item => {
          if(!item.hasOwnProperty('isExpand')){
            this.$set(item,'isExpand',false)
          }
          if(!item.hasOwnProperty('level')){
            this.$set(item,'level',1)
          }

          return item
        })
      },
      sortableIn(key) {
        if (this.sortable === false) {
          return false
        }
        if (this.sortable.includes(key)) {
          return false
        } else {
          return 'custom'
        }
      },
      sortChange(value) {
        const order = {
          ascending: '',
          descending: '-'
        }
        this.$emit('sort-change', { sort_by: `${order[value.order]}${value.prop}` })
      },
      formatter(row, column, item) {
        return fixed3(item)
      },
      getGameType(name){
        return this.parent.chooseOptions.reduce((target = [],item) => {
          if(item.label == name){
            return target.concat(item.value)
          }
          return target
        },[])
      },
      getGameIdList(name){
         return this.parent.chooseOptions.reduce((target = [],item) => {
          if(item.label == name){
            return target.concat(item.child.map(subitem => subitem.value))
          }
          return target
        },[])
      }
    }
  }
</script>
<style>
  .el-table .warning-row .negative{
    color: #f00;
  }
  .el-table .name-level1{
    color:red;
  }
  .el-table .name-level2{
    color:blue;
  }
  .el-table .name-level3{
    color:green;
  }
</style>
